#include "Motor.h"
#include <iostream>

Motor::Motor(const std::string& name) : BaseDriver(name)
{
    m_cond.ResetForVariable();
}

Motor::~Motor()
{
    m_beStop = true;
    m_cond.NotifyForVariable();
}

bool Motor::Init()
{
    StartTask();
    return true;
}

const static int MOTER_CTROL_TIME_INTERVAL = 10;

int Motor::DoTask()
{
    std::cout << "Motor::DoTask() enter" << std::endl;
    // 模拟电机的转速控制
    while (!m_beStop)
    {
        if (m_targetSpeed > m_currentSpeed)         // 加速就控制
        {
            // TODO: 模拟加速
        }
        else if (m_targetSpeed < m_currentSpeed)    // 减速就控制
        {
            // TODO: 模拟加速
        }
        else    // 目标转速与当前转速相等，可能需要设置一个持续使能
        {

        }

        // TODO：可以考虑一些摩擦力等等的影响电机转速的因素


        // 暂时使用理想状态，设置了转速，就能立刻达到目标转速
        m_currentSpeed.store(m_targetSpeed.load());

        m_cond.WaitForVariable(MOTER_CTROL_TIME_INTERVAL);
    }

    std::cout << "Motor::DoTask() exit" << std::endl;
    return 0;
}

void Motor::SetTargetSpeed(ushort rpm)
{
    m_targetSpeed.store(rpm);
    std::cout << "name:" << GetName() << "Motor::SetTargetSpeed . rpm:" << m_targetSpeed.load() << std::endl;
}

ushort Motor::GetCurrentSpeed()
{
    return m_currentSpeed.load();
}